import dao.StudentMapper;
import dao.TeacherMapper;
import entity.Student;
import entity.Teacher;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class main {

    public static void main(String[] args) throws IOException {

        String resouce="resource/mybatis-cfg.xml";
        Reader reader = Resources.getResourceAsReader(resouce);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
//      StudentById(sqlSession);
//        TeacherBiIdStudent(sqlSession);

//        teacherInsert(sqlSession);

        selectByTids(sqlSession);

    }
    //1对1查询
    private static void StudentById(SqlSession sqlSession) {
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //进行多表查询,根据学生的id，查询出对应的老师名称
        Student student = mapper.selectByPrimaryKeyWithTeacher("1");
        System.out.println(student.getTeacher().getTname());
        sqlSession.commit();
        sqlSession.close();
    }

    //1对多查询,查出老师对应的学生
    private static void TeacherBiIdStudent(SqlSession sqlSession) {
      TeacherMapper teacherMapper= sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = teacherMapper.selectByPrimaryKeyWithStuent(5);
        for (int i=0;i<teacher.getStudentList().size();i++){

            System.out.println(teacher.getStudentList().get(i).getSname());
        }
    }

    //需求：在增加teacher的时候，我同时要和新增学生并且绑定，先拿到teacher的tid
    //要求teacher的tid有自增的功能，且为主键
    private static void teacherInsert(SqlSession sqlSession){
        Teacher teacher=new Teacher();
        teacher.setPassword("111");
        teacher.setTname("111老师");
        TeacherMapper teacherMapper=sqlSession.getMapper(TeacherMapper.class);
        teacherMapper.insertSelective(teacher);
        System.out.println("获取到新增老师tid为"+teacher.getTid());

        StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
        //设置学生
        Student student=new Student();
        student.setSid("13");
        student.setSname("绑定测试");
        student.setSagenum(23);
        student.setTid(teacher.getTid());  //对应的
        studentMapper.insertSelective(student);
        sqlSession.commit();
        sqlSession.close();
    }

    //需要查询老师的id是多个的
    private static void  selectByTids(SqlSession sqlSession){
        TeacherMapper teacherMapper=sqlSession.getMapper(TeacherMapper.class);
        List list=new ArrayList();
        list.add(5);
        list.add(12);
        List<Teacher> list1 = teacherMapper.selectByTids(list);
        for (Teacher teacher:list1){
            System.out.println(teacher.getTname());
        }
    }
}
